package com.example.demo.socket.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author: htc
 * @date: Created in 10:57 2018/11/29.
 */
public class ClientDemo {
    private static Logger log = LoggerFactory.getLogger(ClientDemo.class);
    public static final Integer PORT = 9001;
    public static final String HOST = "127.0.0.1";

    /**
     * 发送TCP协议请求
     *
     * @param s
     */
    public static void connectWithTcp(String s) {
        Socket socket = null;
        try {
            socket = new Socket(HOST, PORT);

            //接受服务端发送的数据
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //向服务端发送数据
            PrintStream out = new PrintStream(socket.getOutputStream());
            System.out.println("ready send info to server !!!");
            out.println(s);
            System.out.println("send info to server: " + s);
            //发送后断掉链接
            out.close();
            input.close();
        } catch (IOException e) {
            log.error("客户端链接异常" + e);
        } finally {
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    socket = null;
                    log.error("关闭客户端连接异常：" + e);
                }
            }
        }
    }

    public static void main(String[] args) {
        connectWithTcp("this is socket thread !");
    }
}
